package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

import static cn.wolfcode.wolf2w.domain.Travel.*;

/**
* 游记服务接口实现
*/
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repsitory;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Travel travel) {
        travel.setId(null);
        repsitory.save(travel);
    }

    @Override
    public void update(Travel travel) {
        repsitory.save(travel);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        Travel travel = repsitory.findById(id).orElse(null);
        UserInfo user = userInfoService.get(travel.getUserId());
        travel.setAuthor(user);
        Destination dest = destinationService.get(travel.getDestId());
        travel.setDest(dest);
        return travel;
    }

    @Override
    public List<Travel> list() {
        return repsitory.findAll();
    }

    /*@Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if (qo.getState() > 0){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }
        // 出行时间
        TravelCondition travelDay = TravelCondition.TRAVEL_DAY.get(qo.getDayType());
        if (travelDay != null) {
            query.addCriteria(Criteria.where("day").gte(travelDay.getMin()).lte(travelDay.getMax()));
        }
        // 平均花费
        TravelCondition avgExpend = TravelCondition.AVG_EXPEND.get(qo.getPerExpendType());
        if (avgExpend != null){
            query.addCriteria(Criteria.where("perExpend").gte(avgExpend.getMin()).lte(avgExpend.getMax()));
        }
        Long total = template.count(query, Travel.class);
        if(total == 0){
            return  Page.empty();
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        if (qo.getOrderType() == 1){    // 按照最新排序，发布时间降序
            pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.DESC, "createTime");
        }else if (qo.getOrderType() == 2){  // 最热，按照阅读量降序
            pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.DESC, "viewnum");
        }
        query.with(pageable);
        List<Travel> travels = template.find(query, Travel.class);
        // 通过userID，把author设置进来，通过destId，把dest设置进来
        for (Travel travel : travels) {
            UserInfo user = userInfoService.get(travel.getUserId());
            travel.setAuthor(user);
            Destination destination = destinationService.get(travel.getDestId());
            travel.setDest(destination);
        }
        return new PageImpl(travels, pageable, total);
    }*/

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if (qo.getState() > 0){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }
        // 出行时间
        TravelCondition travelDay = TravelCondition.TRAVEL_DAY.get(qo.getDayType());
        if (travelDay != null) {
            query.addCriteria(Criteria.where("day").gte(travelDay.getMin()).lte(travelDay.getMax()));
        }
        // 平均花费
        TravelCondition avgExpend = TravelCondition.AVG_EXPEND.get(qo.getPerExpendType());
        if (avgExpend != null){
            query.addCriteria(Criteria.where("perExpend").gte(avgExpend.getMin()).lte(avgExpend.getMax()));
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        if (qo.getOrderType() == 1){    // 按照最新排序，发布时间降序
            pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.DESC, "createTime");
        }else if (qo.getOrderType() == 2){  // 最热，按照阅读量降序
            pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.DESC, "viewnum");
        }
        // 通过userID，把author设置进来，通过destId，把dest设置进来
        Page<Travel> travels = DBHelper.query(template, Travel.class, query, pageable);
        for (Travel travel : travels) {
            UserInfo user = userInfoService.get(travel.getUserId());
            travel.setAuthor(user);
            Destination dest = destinationService.get(travel.getDestId());
            travel.setDest(dest);
        }
        return travels;
    }

    @Override
    public void auditTravel(String id, int state) {
        Travel travel = this.get(id);
        // 判断travel 为null，旅游游记的状态不为 待审核
        if (travel == null || travel.getState() != STATE_WAITING ){
            throw new LogicException("参数异常");
        }
        // 状态为发布，审核成功
        if (state == STATE_RELEASE){
            // 修改状态
            travel.setState(STATE_RELEASE);
            // 设置 发布时间
            travel.setReleaseTime(new Date());
            // 设置 最后修改的时间
            travel.setLastUpdateTime(new Date());
        }else if (state == STATE_REJECT){   // 拒绝审核
            travel.setState(STATE_REJECT);
            travel.setReleaseTime(null);
            travel.setLastUpdateTime(new Date());
        }else {
            throw new LogicException("参数异常");
        }
        this.update(travel);
    }

    @Override
    public List<Travel> queryByDestIdOrderByViewnum(String destId) {
        Query query = new Query();
        if (StringUtils.hasLength(destId)){
            query.addCriteria(Criteria.where("destId").is(destId));
        }
        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC, "viewnum");
        query.with(pageable);
        List<Travel> travels = template.find(query, Travel.class);
        return travels;
    }

    @Override
    public List<Travel> queryByDestName(String destName) {
        List<Travel> travels = repsitory.findByDestName(destName);
        for (Travel travel : travels) {
            UserInfo user = userInfoService.get(travel.getUserId());
            travel.setAuthor(user);
            Destination dest = destinationService.get(travel.getDestId());
            travel.setDest(dest);
        }
        return travels;
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        // destName
        Destination dest = destinationService.get(travel.getDestId());
        travel.setDestName(dest.getName());
        // releaseTime
        // lastUpdateTime
        travel.setLastUpdateTime(new Date());
        if(StringUtils.hasLength(travel.getId())){
            Travel travelOld = this.get(travel.getId());
            // viewnum      阅读量
            travel.setViewnum(travelOld.getViewnum());
            // replynum     回复
            travel.setReplynum(travelOld.getReplynum());
            // favornum     点赞
            travel.setFavornum(travelOld.getFavornum());
            // sharenum     分享
            travel.setSharenum(travel.getSharenum());
            // thumbsupnum   收藏
            travel.setThumbsupnum(travelOld.getThumbsupnum());
            // 创建时间也要维护
            travel.setCreateTime(travelOld.getCreateTime());
            //update
            this.update(travel);
        }else{
            // createTime
            travel.setCreateTime(new Date());
            //save
            this.save(travel);
        }
    }
}
